import { formatTime } from '../../utils/DateUtils'
import { calDistance } from '../../utils/LocationUtils'
import { MAPCONFIG } from '../../config/config'
const app = getApp();
const chooseLocationPlugin = requirePlugin('chooseLocation');
const MAPKEY = MAPCONFIG.MAPKEY;//使用在腾讯位置服务申请的key
let timer = null;
Page({
  data: {
    isShowSetting:false,
    CustomBar: app.globalData.CustomBar,
    StatusBar: app.globalData.StatusBar,
    location: app.globalData.location,
    markers:[],
    cardCur:0,
    banner: [{
      id: 0,
      type: 'image',
      appid: '',
      page: '',
      url: 'https://7065-pet-real-1301063915.tcb.qcloud.la/public/images/banner/banner0.png'
    }],
    lastRecord: []
  },
  onLoad: function () {
    this.getLocation();
    this.getBanner();
    this.getLastRecord();
    this.getNearbyRecord();
    this.mapCtx = wx.createMapContext('homeMap');
  },
  onShow(){
    const location = chooseLocationPlugin.getLocation();
    if (location) {
      //console.log(location);
      this.setData({ location: location });
      app.globalData.location = location;
      this.getLastRecord(location);
      this.getNearbyRecord(location);
    }
  },
  getBanner() {
    wx.cloud.callFunction({
      name: 'base',
      data: {
        action: 'getBanner',
        geo: app.globalData.location,
        version:app.globalData.version
      },
      success: res => {
        console.log('[云函数] [getBanner] : ', res)
        if (res && res.result && res.result.code == 1) {
          this.setData({
            banner: res.result.data
          });
        }
      }
    })
  },
  getLastRecord(location) {
    const geo = location ? location : app.globalData.location;
    wx.cloud.callFunction({
      name: 'base',
      data: {
        action: 'getLastRecord',
        geo: geo,
        version: app.globalData.version
      },
      success: res => {
        console.log('[云函数] [getLastRecord] : ', res)
        if (res && res.result && res.result.code == 1){
          let lastRecord = res.result.data;
          lastRecord.forEach((item,index) => {
            item.time     = formatTime(item.createTime)
            item.distance = calDistance(item.location, app.globalData.location)
          })
          this.setData({
            lastRecord: lastRecord
          });
        }

      }
    })
  },
  getNearbyRecord(location){
    const geo = location ? location : app.globalData.location;
    wx.cloud.callFunction({
      name: 'base',
      data: {
        action: 'getNearbyRecord',
        geo: geo,
        version: app.globalData.version
      },
      success: res => {
        console.log('[云函数] [getNearbyRecord] : ', res)
        if (res && res.result && res.result.code == 1) {
          let markers = res.result.data;
          // markers.forEach((item, index) => {
          //   item.time = formatTime(item.createTime)
          // })
          this.setData({
            markers: markers
          });
        }
      }
    })
  },
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },
  tapBanner(e){
    const index = e.currentTarget.dataset.index;
    const banner = this.data.banner[index];
    const appid  = banner.appid;
    const page   = banner.page;
    const url    = banner.url;
    if(appid){
      wx.navigateToMiniProgram({
        appId: appid,
        path: page,
        extraData: {
          from: 'pet'
        },
        envVersion: 'release'
      })
    }else{
      if(page){
        wx.navigateTo({
          url: page
        })
      }
    }
    if(!appid && !page){
      wx.previewImage({
        urls: [url]
      });
    }

  },
  tapMarker(e){
    console.log(e.markerId);
    const markerId = e.markerId;
    const marker = this.data.markers.find((item) => {
      return item.id == markerId
    })
    const id = marker._id;
    wx.showModal({
      title: '查看求助',
      content: `打开${marker.petName||'TA'}的求助信息？`,
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/record/detail?id=' + id
          })
        }
      }
    })

  },
  goDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/record/detail?id=' + id
    })
  },
  mapRegionChange(e){
    if (e.type == 'end'){
      this.mapCtx.getCenterLocation({
        success:res => {
          const location = {
            latitude: res.latitude,
            longitude: res.longitude,
          }
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(() => {
            //this.getLastRecord(location);
            this.getNearbyRecord(location);
          }, 500);
        }
      })
    }
  },
  getLocation(){
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success: res => {
        app.globalData.location = res;
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${MAPKEY}&get_poi=0`, 
          success : ret => {
            if (ret && ret.data && ret.data.status == 0){
              const poi = ret.data.result;
              let location = {name: "", latitude: 30.265551, longitude: 120.153603, city: "杭州市", address: "" };
              location.city = poi.address_component.city;
              location.address = poi.address;
              location.latitude = res.latitude;
              location.longitude = res.longitude;
              that.setData({ location: location });
              app.globalData.location = location;
              that.getLastRecord(location);
              //that.getNearbyRecord(location); //通过mapRegionChange触发
            }
          }
        })
      },
      fail: err => {
        console.log(err);//无权限：getLocation:fail auth deny  || getLocation:fail authorize no response
        if (err && err.errMsg && err.errMsg.includes("auth") ){
          wx.navigateTo({
            url: '/pages/mine/auth?setting=true'
          })
        }
      }
    })
  },
  chooseLocation(e){
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${MAPKEY}&referer=留守宠物`
    });
  },
  onShareAppMessage() {
    return {
      title: '快来看看附近需要帮助的宠物',
      path: '/pages/index/index',
      imageUrl: '/images/share.jpg'
    }
  }
})